# $Id: http.py 7557b5d4d82b 2012/12/02 09:07:16 pgurumur $
# Copyright (c) 2009 Prabhu Gurumurthy  <pgurumur@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

__version__ = "$Revision: 7557b5d4d82b $"
__author__ = "$Author: pgurumur $"

from django.db.models.base import ModelBase
from django.http import HttpResponse
from django.utils import simplejson
from django.utils.encoding import force_unicode

from aptools import utils
from aptools.lib import stdlib

def serialize_json(Object, *Args, **kwargs):
   ensure_ascii = False
   cls = JSONEncoder

   kwargs['ensure_ascii'] = kwargs.get('ensure_ascii', False)
   kwargs['cls'] = kwargs.get('cls', JSONEncoder)

   return simplejson.dumps(Object, *Args, **kwargs)

class JSONEncoder(simplejson.JSONEncoder):
   def default(self, Object):
      try:
         iterable = iter(Object)
      except TypeError:
         pass
      else:
         return list(iterable)

      try:
         isinstance(stdlib.my_class(Object), ModelBase)
      except Exception:
         pass
      else:
         return force_unicode(Object)

      flag = False
      try:
         if hasattr(Object, '__unicode__') or hasattr(Object, '__str__'):
            flag = True
      except Exception:
         pass
      else:
         if flag:
            return force_unicode(Object)

      return super(stdlib.my_class(self), self).default(Object)

class JSONResponse(HttpResponse):
   def __init__(self, content = '', json_opts = {},
         mimetype = 'application/json', *args, **kwargs):

      self.log = utils.loghandle(stdlib.my_name(self))
      self._content = content
      if content:
         content = serialize_json(content, **json_opts)
      else:
         content = serialize_json([], **json_opts)

      super(stdlib.my_class(self), self).__init__(
            content, mimetype, *args, **kwargs)

   def __str__(self):
      return str(self._content).encode('utf-8')

   def __repr__(self):
      return repr(str(self))

   def __unicode__(self):
      return unicode(str(self))

